<script setup>
import { ref } from 'vue'
import api from '@/api'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh'
dayjs.locale('zh')
dayjs.extend(relativeTime)

const router = useRouter()
const route = useRoute()

const materials = ref([])
const materialsPage = ref(1)
const materialsTotal = ref(0)
const materialsLoading = ref(false)
const materialsFinished = ref(false)
const materialsRefreshing = ref(false)

const getMaterials = async () => {
  materialsLoading.value = true
  materialsPage.value = 1
  materialsFinished.value = false
  materials.value = []
  materialsTotal.value = 0
  try {
    const resp = await api.get('ip/materials/favorites')
    materials.value = resp.data
    materialsTotal.value = resp.total
    if (materials.value.length == resp.total) {
      materialsFinished.value = true
    }
  } catch (error) {
    console.error(error)
  }
  materialsLoading.value = false
  materialsRefreshing.value = false
}

const onLoad = async () => {
  if (!materialsFinished.value) {
    try {
      materialsPage.value += 1
      const resp = await api.get('ip/materials/favorites', { params: { page: materialsPage.value } })
      if (resp.data.length) {
        materials.value.push(...resp.data)
        materialsTotal.value = resp.total
      } else {
        materialsFinished.value = true
      }
    } catch (error) {
      console.error(error)
    }
  }
  materialsLoading.value = false
}

const onRefresh = async () => {
  getMaterials()
}

getMaterials()
</script>

<template>
  <van-pull-refresh class="list" v-model="materialsRefreshing" @refresh="onRefresh">
    <van-list v-model:loading="materialsLoading" :finished="materialsFinished" :finished-text="materials.length && !materialsLoading ? '没有更多了' : '暂无素材'" @load="onLoad">
      <div class="materials">
        <div class="material" v-for="item in materials" @click="router.push(`/ip/materials/${item.material.id}`)">
          <div class="body">
            <div class="title">{{ item.material.title }}</div>
            <div class="content">{{ item.material.content }}</div>
            <div class="footer">
              <div class="category-name">{{ item.material.category.name }}</div>

              <div class="count">
                <img src="@/assets/img/sc.png" />
                {{ item.material.favorite_count }}
              </div>

              <div class="count">
                <img src="@/assets/img/tk.png" />
                {{ item.material.video_count }}
              </div>
              <div class="count">{{ dayjs(item.material.created_at).fromNow() }}</div>
            </div>
          </div>
          <div class="image">
            <img :src="item.material.image" />
          </div>
        </div>
      </div>
    </van-list>
  </van-pull-refresh>
</template>

<style lang="scss" scoped>
.list {
  height: 100vh;
}
</style>
